package com.sxhuayuan.parking.compenent.shiro.realm;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import com.sxhuayuan.parking.compenent.shiro.AccountType;
import com.sxhuayuan.parking.compenent.shiro.AuthenticationToken;
import com.sxhuayuan.parking.compenent.shiro.Principal;

@Component("memberAuthenticationRealm")
public class MemberAuthenticationRealm extends AuthorizingRealm {

	@Override
	public String getName() {
		return "member";
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken token) throws AuthenticationException {
		AuthenticationToken authenticationToken = (AuthenticationToken) token;
		String username = authenticationToken.getUsername();
		Long id = Long.valueOf(username.split("@@")[0]);
		String nickname = username.split("@@")[1];
		if (StringUtils.isEmpty(username) || authenticationToken.getPassword() == null)
			throw new IncorrectCredentialsException();
		String password = new String(authenticationToken.getPassword());
		if (username != null && password != null) {
			return new SimpleAuthenticationInfo(new Principal(AccountType.member, id, nickname), password, getName());
		}
		throw new UnknownAccountException();
	}

}
